package com.jtzc.mcp.csdn.infrastructure.adapter;

import com.jtzc.mcp.csdn.domain.adapter.ICSDNPort;
import com.jtzc.mcp.csdn.domain.model.ArticlePublishRequest;
import com.jtzc.mcp.csdn.domain.model.ArticlePublishResponse;
import com.jtzc.mcp.csdn.infrastructure.gateway.ICSDNService;
import com.jtzc.mcp.csdn.infrastructure.gateway.dto.ArticlePublishRequestDTO;
import com.jtzc.mcp.csdn.infrastructure.gateway.dto.ArticlePublishResponseDTO;
import com.alibaba.fastjson2.JSON;
import com.jtzc.mcp.csdn.types.properties.CSDNApiConfigProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;


@Slf4j
@Component
public class CSDNPort implements ICSDNPort {

    @Resource
    private CSDNApiConfigProperties properties;

    @Resource
    private ICSDNService csdnService;

    @Override
    public ArticlePublishResponse writeArticle(ArticlePublishRequest request) throws IOException {
        ArticlePublishRequestDTO requestDTO = new ArticlePublishRequestDTO();
        requestDTO.setTitle(request.getTitle());
        requestDTO.setMarkdowncontent(request.getMarkDownContent());
        requestDTO.setContent(request.getContent());
        requestDTO.setTags(request.getTags());
        requestDTO.setDescription(request.getDescription());
        requestDTO.setCategories(properties.getCategories());

        // 优先使用配置中的cookie（可能来自命令行参数），如果没有则使用请求参数中的cookie
        String cookieToUse = properties.getCookie();
        if (cookieToUse == null || cookieToUse.trim().isEmpty()) {
            cookieToUse = request.getCookie();
        }

        if (cookieToUse == null || cookieToUse.trim().isEmpty()) {
            throw new IllegalArgumentException("Cookie is required! Please provide it either via command line --cookie parameter or in the request body.");
        }

        Call<ArticlePublishResponseDTO> call = csdnService.saveArticle(requestDTO, cookieToUse);
        Response<ArticlePublishResponseDTO> response = call.execute();
        log.info("请求CSDN发帖 \n req:{} \n res:{}", JSON.toJSONString(requestDTO), JSON.toJSONString(response));
        if (response.isSuccessful()) {
            ArticlePublishResponseDTO responseDTO = response.body();
            if (null == responseDTO) {
                return null;
            }
            ArticlePublishResponse articlePublishResponse = new ArticlePublishResponse();
            articlePublishResponse.setCode(responseDTO.getCode());
            articlePublishResponse.setMsg(responseDTO.getMsg());

            return articlePublishResponse;
        }

        return null;
    }

}
